﻿#region Copyright information
// 
// Copyright © 2005-2013 Yongkee Cho. All rights reserved.
// 
// This code is a part of the Biological Object Library and governed under the terms of the
// GNU Lesser General  Public License (LGPL) version 2.1 which accompanies this distribution.
// For more information on the LGPL, please visit http://bol.codeplex.com/license.
// 
// - Filename: BinSizeMethod.cs
// - Author: Yongkee Cho
// - Email: yongkeecho@gmail.com
// - Date Created: 2012-09-06 11:39 AM
// - Last Modified: 2013-01-25 3:59 PM
// 
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using BOL.Linq.Descriptive;
using BOL.Maths.Distributions;

namespace BOL.Linq.Transformation
{
    public enum BinSizeMethod
    {
        Sturges,
        Scotts,
        SquareRoot,
        FreedmanDiaconis
    }

    public static partial class Binning
    {
        private static int GetBinSize(this IEnumerable<double> source, BinSizeMethod method)
        {
            var list = source.ToList();
            var length = list.Count;

            switch (method)
            {
                default:
                    return (int)Math.Ceiling(Math.Log(length, 2) + 1);
                case BinSizeMethod.Scotts:
                    return (int)(0.2857143 * length * Math.Pow(length, 0.3333333) / list.StandardDeviation());
                case BinSizeMethod.SquareRoot:
                    return (int) Math.Sqrt(length);
                case BinSizeMethod.FreedmanDiaconis:
                    var gaussian = GaussianDistribution.StandardDistribution;
                    gaussian.MaximumLikelihoodEstimate(list);
                    var sigma = gaussian.Sigma;
                    var iqr = 1.349 * sigma;
                    return (int) (length * Math.Pow(length, 0.3333333) / iqr);
            }
        }
    }
}
